package service

import (
	cmodel "ksd-social-api/modules/channel/model"
	context3 "ksd-social-api/modules/msg/model/context"
)

/**
 * 用户购买课程
 * @author feige
 * @date 2023-11-23
 * @version 1.0
 * @desc
 */
type UserBuyChannelService struct {
}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc  判断用户是否购买此课程
 */
func (service *UserBuyChannelService) CountUserBuyChannel(userId uint64, channelId uint64, systemId uint64) bool {
	// 1： 判断用户是否购买此课程，如果购买过了就就不要去保存订单
	isBuyFlag := userBuyChannelMapper.CountUserBuyChannelNo(userId, channelId, systemId)
	return isBuyFlag == 0
}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc  保存用户购买专栏信息
 */
func (service *UserBuyChannelService) SaveUserBuyChannel(
	OutTradeNo string, TransactionId string, orderJson string, payMethod int, payMethodName string, price string,
	userId uint64, opid uint64, systemId uint64, systemName string) bool {
	// 1： 判断用户是否购买此课程，如果购买过了就就不要去保存订单
	isBuyFlag := userBuyChannelMapper.CountUserBuyChannelNo(userId, opid, systemId)
	if isBuyFlag == 0 {
		userBuyChannel := cmodel.UserBuyChannel{}
		// 根据课程id查询课程信息
		channel, _ := userBuyChannelMapper.GetById(opid, systemId)
		userVo := userMapper.GetUserByID(userId, systemId)

		userBuyChannel.SystemId = systemId
		userBuyChannel.SystemName = systemName
		// 处理返回结果
		userBuyChannel.ChannelId = opid
		userBuyChannel.Title = channel.Title
		userBuyChannel.Cover = ""

		userBuyChannel.UserId = userId
		userBuyChannel.Username = userVo.Username
		userBuyChannel.Avatar = userVo.Avatar
		userBuyChannel.Uuid = userVo.Uuid
		userBuyChannel.Phone = userVo.Telephone
		userBuyChannel.Address = userVo.Address
		userBuyChannel.Nickname = userVo.Nickname

		userBuyChannel.Code = ""
		userBuyChannel.PayMethod = payMethod
		userBuyChannel.PayMethodName = payMethodName
		userBuyChannel.Tradeno = OutTradeNo
		userBuyChannel.Orderno = TransactionId
		userBuyChannel.OrderJson = orderJson
		userBuyChannel.Price = price
		userBuyChannelMapper.SaveUserBuyChannel(userBuyChannel)

		// 保存消息
		messageMeContext := context3.MessageMeContext{}
		messageMeContext.UserId = userId
		messageMeContext.Title = channel.Title
		messageMeContext.Uuid = userVo.Uuid
		messageMeContext.SystemId = systemId
		messageMeContext.SystemName = "系统512"
		messageMeContext.Username = userVo.Nickname
		messageMeContext.Url = "https://www.study512.com" + channel.Url
		messageMeService.SaveMessageMeChannel(&messageMeContext)
		return true
	}
	return false
}
